package com.atguigu.flink.chapter06.state.operator;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author lzc
 * @Date 2023/6/25 11:24
 */
public class OperatorListStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
    
        env.enableCheckpointing(3000);
        
        
        env
            .socketTextStream("hadoop162", 8888)
            .map(new MyMapFunction())
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static class MyMapFunction implements MapFunction<String, String> , CheckpointedFunction {
        List<String> list = new ArrayList<>();
        private ListState<String> state;
    
        @Override
        public String map(String value) throws Exception {
            if (value.contains("x")) {
                throw  new RuntimeException("程序碰到异常....");
            }
    
            String[] words = value.split(" ");
            Collections.addAll(list, words);
            return list.toString();
        }
    
        // 把转态中的值持久化保存起来
        // 周期性的执行:每个并行度执行一次
        @Override
        public void snapshotState(FunctionSnapshotContext ctx) throws Exception {
//            System.out.println("MyMapFunction.snapshotState");
            state.update(list);
           // state.addAll(); // a b c  a b c
           // state.add();
           
        }
        
        // 初始化状态: 从状态中取出数据, 存入到你自己需要的数据结构中
        // 程序启动的时候每个并行度执行一次
        @Override
        public void initializeState(FunctionInitializationContext ctx) throws Exception {
            System.out.println("MyMapFunction.initializeState");
            // 获取算子状态中的列表状态
            state = ctx.getOperatorStateStore().getListState(new ListStateDescriptor<String>("word", String.class));
            Iterable<String> it = state.get();
            for (String word : it) {
                System.out.println("恢复.... " + word);
                list.add(word);
            }
        }
    }
    
    
}
